package cn.tedu.emqx.demo.config;

import cn.tedu.emqx.demo.emqx.MyMqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;

@Configuration
public class MqttClientConfig {
    @Value("${charging.emqx.address}")
    private String address;
    @Value("${charging.emqx.username}")
    private String username;
    @Value("${charging.emqx.password}")
    private String password;

    @Bean
    public MqttClient mqttClientInit() {
        MqttClient mqttClient = null;
        try {
            // 给对象初始化赋值、实例化对象,告诉客户端emqx地址（并且客户端对象的id要保证唯一）
            mqttClient = new MqttClient(address, UUID.randomUUID().toString(), new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            // 作为了解
            options.setCleanSession(true); // 清空会话
            options.setKeepAliveInterval(60); // 心跳时间隔60秒（用于检测客户端是否在线）
            options.setConnectionTimeout(60); // 连接超时时间10秒（设置等待建立连接的最大时长）
            options.setAutomaticReconnect(true); // 自动重连
            // 提供一个回调对象
            mqttClient.setCallback(new MyMqttCallback(mqttClient));
            mqttClient.connect(options); // 发起连接
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mqttClient;
    }
}
